package top.wangjiu.reactive.rpc.server;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import top.wangjiu.reactive.rpc.config.ServerConfiguration;
import top.wangjiu.reactive.rpc.decode.RpcRequestDecoder;
import top.wangjiu.reactive.rpc.encode.RpcResponseEncoder;
import java.net.InetSocketAddress;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class RpcServer {

    private static final Log log = LogFactory.getLog(RpcServer.class);

    private final ServerBootstrap bootstrap;
    private final NioEventLoopGroup bossGroup;
    private final NioEventLoopGroup workGroup;
    private final ServerConfiguration configuration;
    private final InetSocketAddress inetSocketAddress;
    private volatile Channel serverChannel;

    public RpcServer(ServerConfiguration configuration){

        this.configuration = configuration;
        //daemon true 在主线程退出后，守护线程也退出
        bossGroup = new NioEventLoopGroup(1,new DefaultThreadFactory(getClass(),true));
        workGroup = new NioEventLoopGroup(new DefaultThreadFactory(getClass(),true));
        bootstrap =new ServerBootstrap();
        bootstrap.group(bossGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new RpcRequestDecoder());
                        ch.pipeline().addLast(new RpcResponseEncoder());
                        ch.pipeline().addLast(new IdleStateHandler(0,0,configuration.getConnectAliveTimeoutSecond()));
                        ch.pipeline().addLast(new ServerHander(configuration));
                    }
                });
        configuration.getOptions().forEach(bootstrap::option);
        configuration.getChildOptions().forEach(bootstrap::childOption);
        configuration.getAttrs().forEach(bootstrap::attr);
        inetSocketAddress = configuration.getServerAddress();
    }

    public void start() {
        try {
            ChannelFuture future = bootstrap.bind(inetSocketAddress).sync();
            log.info("reactive rpc server started on port " + getPort());
            serverChannel = future.channel();
        } catch (InterruptedException e) {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    public void stop() {
        try {
            if(serverChannel!=null){
                serverChannel.close();
                waitStop();
            }
        } catch (InterruptedException e) {
            log.error("server stop exception",e);
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    public int getPort() {
        return inetSocketAddress.getPort();
    }

    public void waitStop() throws InterruptedException {
        serverChannel.closeFuture().sync();
    }
}
